#!/usr/bin/env bash

source "$(realpath $(dirname $0))/inc/common.sh"

if [ -z "$(command -v base64)" ]; then
	echo 'This script needs base64 binary. Please install base64 package. Exiting...'; exit 2953
fi
if [ -z "$(command -v openvpn)" ]; then
	echo 'This script needs openvpn. Please install openvpn package. Exiting...'; exit 2831
fi

WRITE_OUTPUT=0
if [ -f "$CSVOUTPUT" ]; then
	is_file_stale "$CSVOUTPUT"
	if [ "$?" -gt 0 ]; then
		if $auto_update_when_stale; then
			WRITE_OUTPUT=1
		else
			read -e -p "CSV data is older than $stale_threshold_hours hour(s). Do you want to download the latest version? [Y/n] " choice
			if [[ ! "$choice" == [Nn]* ]]; then # ! means default is Y
				WRITE_OUTPUT=1
			fi
		fi
	else
		read -e -p "CSV data is already there. Do you want to download the latest version? [y/N] " choice
		if [[ "$choice" == [Yy]* ]]; then
			WRITE_OUTPUT=1
		fi
	fi
else
	WRITE_OUTPUT=1
fi
if [ "$WRITE_OUTPUT" -gt 0 ]; then
	echo '== Downloading latest VPN connections data...'
	if [ -x "$(command -v curl)" ]; then
		curl -L 'http://www.vpngate.net/api/iphone/' -o "$CSVOUTPUT"
	elif [ -x "$(command -v wget)" ]; then
		wget 'http://www.vpngate.net/api/iphone/' -o "$CSVOUTPUT"
	else
		echo 'curl or wget is required. Exiting...'; exit 9437
	fi
fi

# Trim the vpn csv data
# First 2 lines are just data type, column name etc. so we use $csv_offset to get rid of them.
# Columns:
#  01. #HostName
#  02. IP
#  03. Score
#  04. Ping
#  05. Speed
#  06. CountryLong
#  07. CountryShort
#  08. NumVpnSessions
#  09. Uptime
#  10. TotalUsers
#  11. TotalTraffic
#  12. LogType
#  13. Operator
#  14. Message
#  15. OpenVPN_ConfigData_Base64
csv_text=$(head -n $(( $ovpn_count + $csv_offset )) "$CSVOUTPUT" | tail -n -$ovpn_count)

rm -rf "$DATADIR_OVPNS"
mkdir -p "$DATADIR_OVPNS"

count=0
echo "$csv_text" | while read -r line ; do
    ((count++))
    # CountryShort|Score|Ping|Speed
    echo "$line" | awk -F',' -v count="$count" '{ print count ".\t" $7 "\t" $3 "\t" $4 "ms \t" $5/1000/1000 "mbps" }' >> "$DATADIR_OVPNS/ovpns.list"

    if [ ! -z "$(base64 --help | grep 'i, --ignore-garbage')" ]; then # GNU+Linux
        ignore_error_option='i'
    else # BSD etc.
        ignore_error_option='n'
    fi
    echo "$line" | awk -F',' '{ print $15 }' | base64 -d${ignore_error_option} > "$DATADIR_OVPNS/$count.ovpn"
done
